package com.huawei.admins.platform.gateway.core.server.reactor;

import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import org.jetbrains.annotations.NotNull;

public class ProxyFrontendHandler extends ChannelInboundHandlerAdapter {

    private final String remoteHost;

    private final int remotePort;

    private final Channel backendChannel;

    public ProxyFrontendHandler(String remoteHost, int remotePort, Channel backendChannel) {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
        this.backendChannel = backendChannel;
    }

    @Override
    public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception {

        if (backendChannel.isActive()) {
            backendChannel.writeAndFlush(msg).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            });
        }

    }

    @Override
    public void channelInactive(@NotNull ChannelHandlerContext ctx) throws Exception {
        if (backendChannel != null) {
            closeOnFlush(backendChannel);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        closeOnFlush(ctx.channel());
    }

    public static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

    public String getRemoteHost() {
        return remoteHost;
    }

    public int getRemotePort() {
        return remotePort;
    }

    public Channel getBackendChannel() {
        return backendChannel;
    }
}
